package com.yanqu.road.server.helper;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.utils.MD5Security;
import com.yanqu.road.utils.string.StringUtils;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author duli
 * @version 1.0
 * @date 2020/9/7 13:18
 * @Description 字符转换
 */
public class ChatHelper {
    private static Pattern humpPattern = Pattern.compile("[A-Z]");
    /** JSONObject 驼峰转下划线 */
    public static JSONObject getHumpToLineParamMap(JSONObject paramObj){
        JSONObject object=new JSONObject();
        for(Map.Entry<String, Object> dataEntry : paramObj.entrySet()){
            String key = dataEntry.getKey();
            Object value = dataEntry.getValue();
            if(null != value){
                object.put(ChatHelper.humpToLine2(key), dataEntry.getValue().toString());
            }
        }
        return object;
    }
    /** 驼峰转下划线 */
    public static String humpToLine2(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


    public static String getUrlData(SortedMap<String, String> paramMap) {
        StringBuffer sb = new StringBuffer();
        for(Map.Entry<String, String> dataEntry : paramMap.entrySet()){
            String key = dataEntry.getKey();
            String value = dataEntry.getValue();
            if(!StringUtils.isNullOrEmpty(value)){
                sb.append(key + "=" + value + "&");
            }
        }
        if(sb.length() > 0){
            sb.deleteCharAt(sb.length() - 1);
        }
        return String.valueOf(sb);
    }


}
